package com.simpletour.qa.gateway.controller;

import com.simpletour.qa.common.entity.User;
import com.simpletour.qa.common.http.ObjectRestResponse;
import com.simpletour.qa.common.http.ResponseCode;
import com.simpletour.qa.common.http.ResponseMsg;
import com.simpletour.qa.common.util.SHAEncrypt;
import com.simpletour.qa.gateway.dto.LoginParam;
import com.simpletour.qa.gateway.jwt.ClaimsUtil;
import com.simpletour.qa.gateway.jwt.JwtTokenUtil;
import com.simpletour.qa.gateway.rpc.IUserService;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * 用户授权
 * @author zhaohw
 * @date 2018-06-19 15:16
 */
@RestController
@RequestMapping("/auth")
@Slf4j
public class AuthController {

    @Autowired
    private IUserService iUserService;

    @Value("${gate.jwt.header}")
    private String tokenHeader;

    /**
     * 校验用户 生成JWT
     * @param loginParam
     * @return
     */
    @RequestMapping(value = "login", method = RequestMethod.POST)
    public ObjectRestResponse login(@RequestBody LoginParam loginParam) {
        User user = iUserService.findUserByUsername(loginParam.getUsername());
        if(user==null){
            return ObjectRestResponse.builder().code(ResponseCode.USER_NOT_EXIST).msg(ResponseMsg.USER_NOT_EXIST).build();
        }
        if(User.USER_STATUS_FORBIDDEN.equals(user.getStatus())){
            return ObjectRestResponse.builder().code(ResponseCode.USER_FORBIDDEN).msg(ResponseMsg.USER_FORBIDDEN).build();
        }
        try {
            if(!user.getPassword().equals(SHAEncrypt.encryptSHA(loginParam.getPassword()))){
                return ObjectRestResponse.builder().code(ResponseCode.USER_PASSWORD_ERROR).msg(ResponseMsg.USER_PASSWORD_ERROR).build();
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            return ObjectRestResponse.builder().code(ResponseCode.SERVER_INTERNAL_ERROR).msg(ResponseMsg.SERVER_INTERNAL_ERROR).build();
        }
        String jwt = JwtTokenUtil.generateToken(user);
        return ObjectRestResponse.builder().code(ResponseCode.SUCCESS).msg(ResponseMsg.SUCCESS).result(jwt).build();
    }

    /**
     * 通过JWT获取个人信息
     * @param
     * @return
     */
    @RequestMapping(value = "info", method = RequestMethod.GET)
    public ObjectRestResponse info(HttpServletRequest request) {
        String jwt = request.getHeader(tokenHeader);
        Claims claims = JwtTokenUtil.getClaimsFromToken(jwt);
        Object userId = claims.get(ClaimsUtil.CLAIM_KEY_USER_ID);
        User user = iUserService.findUserByUserId(Integer.parseInt(userId.toString()));
        return ObjectRestResponse.builder().code(ResponseCode.SUCCESS).result(user).build();
    }


//    @ApiOperation(value="用户注销",notes = "销毁token")
//    @RequestMapping(value = "logout", method = RequestMethod.GET)
//    public ObjectRestResponse logout(
//            String username,String password) {
//        String jwt = (String) redisTemplate.opsForValue().get("user");
//        System.out.println(jwt);
//        return new ObjectRestResponse().code(200).result(jwt);
//    }

}
